﻿using DryIoc;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Common;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WheelClean2.Model;
using WheelClean2.Mould;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace WheelClean.ViewModels
{
    class TraceListViewModel : BindableBase, INavigationAware
    {
        private readonly IDialogService _dialog;
        private ObservableCollection<Track> _Infos;

        /// <summary>
        /// 设备列表
        /// </summary>
        public ObservableCollection<Track> Infos
        {
            get { return _Infos; }
            set { SetProperty(ref _Infos, value); }
        }

        private ObservableCollection<TraceLists> _lists;
        /// <summary>
        /// 设备列表
        /// </summary>
        public ObservableCollection<TraceLists> Lists
        {
            get { return _lists; }
            set { SetProperty(ref _lists, value); }
        }

        private string _addName;
        /// <summary>
        /// 新增轨迹名称
        /// </summary>
        public string AddName
        {
            get { return _addName; }
            set { SetProperty(ref _addName, value); }
        }

        private TraceLists _item;
        /// <summary>
        /// 轨迹编号选择
        /// </summary>
        public TraceLists Item
        {
            get { return _item; }
            set { 
                SetProperty(ref _item, value);
                if(value!=null)
                {
                    Infos = new ObservableCollection<Track>();
                    var date = context.Tracks.Where(t => t.TrackListNumber == value.ID).OrderBy(t => t.Number).ToList();
                    Infos.AddRange(date);
                }
            }
        }

        private List<Track> trackSave;

        private AppDbContext context;
        public DelegateCommand<string> DelegateCommand_Open { get; private set; }

        public DelegateCommand<bool?> DelegateCommand_Dialog { get; private set; }

        public DelegateCommand DelegateCommand_Deteled { get; private set; }

        public DelegateCommand DelegateCommand_Send { get; private set; }
        

        TraceListViewModel(IDialogService dialog)
        {
            context = new AppDbContext();
            _dialog = dialog;
            DelegateCommand_Open = new DelegateCommand<string>(Open);
            DelegateCommand_Dialog = new DelegateCommand<bool?>(DialogSwitch);
            DelegateCommand_Deteled = new DelegateCommand(Deteled);
            DelegateCommand_Send = new DelegateCommand(Send);
            GetData();
            trackSave = new List<Track>();
        }

        private void Send()
        {
            ModbusTCP.SendTraceInfos(Infos.ToList());
        }

        /// <summary>
        /// 获取页面数据
        /// </summary>
        public void GetData()
        {
            try
            {
                Item = null;
                if (Lists == null)
                {
                    Lists = new ObservableCollection<TraceLists>();
                }
                else
                {
                    Lists.Clear();

                }
                Lists.AddRange(context.TraceLists.ToList());
                if (Lists != null && Lists.Count > 0)
                    Item = Lists[0];
                Infos = new ObservableCollection<Track>();
                var date = context.Tracks.Where(t => t.TrackListNumber == Item.ID).OrderBy(t => t.Number).ToList();
                Infos.AddRange(date);
            }
            catch(Exception e)
            {

            }
  
        }
        /// <summary>
        /// 删除轨迹
        /// </summary>
        /// <param name="obj"></param>
     
        private void Deteled()
        {
 
            //数据库删除
            context.TraceLists.Remove(Item);
            //从表删除
            context.Tracks.RemoveRange(Infos.ToList());
            context.SaveChanges();
            //重新获取页面数据
            GetData();







        }

        private void DialogSwitch(bool? obj)
        {
            var data = new TraceLists() {  Name = AddName };
            //新增数据库
            context.TraceLists.Add(data);
            context.SaveChanges();
            //页面新增
            Lists.Add(data);
            AddName = "";
            Item = data;

            //DialogHost.Close( new DialogResult(ButtonResult.Cancel));
        }

        private void Open(string obj)
        {

            // viewName 可能是 "HomeView", "SettingsView", "AboutView" 等
            if (!string.IsNullOrEmpty(obj))
            {
                if (obj == "add")
                {
                    DialogParameters parameters = new DialogParameters();
                    parameters.Add("max", Infos.Count==0?0: Infos.Max(t => t.Number));
                    // 导航到 ContentRegion 中指定的视图
                    _dialog.ShowDialog("TraceInfo", parameters, (t) => {
                        if (t.Result == ButtonResult.OK)
                        {
                           
                            if (t.Parameters.ContainsKey("info"))
                            {
                                var info = t.Parameters.GetValue<Track>("info");
                                if (info != null)
                                {
                                    //选定当前轨迹
                                    info.TrackListNumber = Item.ID;
                                    //页面列表新增
                                    Infos.Add(info);
                                    //数据库新增
                                    context.Tracks.Add(info);
                                    context.SaveChanges();
                                }

                            }
                        }
                    
                    
                    });
                }
                else if (obj == "edit")
                {
                    DialogParameters parameters = new DialogParameters();
                    var info = Infos.FirstOrDefault(t => t.IsSelected);
                    if (info != null)
                    {
                        parameters.Add("info", Infos.FirstOrDefault(t => t.IsSelected));
                    }
                    else
                    {
                        var result = MessageBox.Show("必须选择一个步", "警告");
                        return;
                    
                    }
                    // 导航到 ContentRegion 中指定的视图
                    _dialog.ShowDialog("TraceInfo", parameters, (t) => { 
                        if(t.Result==ButtonResult.OK)
                        {
                            if(t.Parameters.ContainsKey("info"))
                            {
                                info = t.Parameters.GetValue<Track>("info");
                            }
                            
                        }
                    });
                }
                else if (obj== "copy")
                {
                    //获取所有被选择的
                    var data = Infos.Where(t => t.IsSelected).ToList();
                 
                    trackSave = JsonConvert.DeserializeObject<List<Track>>(JsonConvert.SerializeObject(data));
                    trackSave.ForEach(t => t.ID = 0);
                    //取消页面选择状态
                    data.ForEach(t => t.IsSelected = false);

                }
                else if(obj == "insert")
                {
                    var data = Infos.FirstOrDefault(t => t.IsSelected);
                    if(data==null)
                    {
                        MessageBox.Show("请选择插入的位置");
                    }
                    else
                    {
                        //获取位置
                        var number = data.Number;
                        var list1 = Infos.Take(number).ToList();
                        var list2 = Infos.TakeLast(Infos.Count- number).ToList();
                        trackSave.AddRange(list2);
                        //赋值序号
                        int num = 1;
                        trackSave.ForEach(t =>
                        {
                            t.Number = number + num;
                            num++;
                        });
                        //重新组合列表
                        Infos.Clear();
                        Infos.AddRange(list1);
                        Infos.AddRange(trackSave);
                        //更新数据库
                        context.Tracks.UpdateRange(Infos.ToList());
                        context.SaveChanges();
                        //取消页面选择状态
                        Infos.ToList().ForEach(t => t.IsSelected = false);






                    }
                }
                else if (obj == "delete")
                {
                    //获取所有被选择的
                    var data = Infos.Where(t => t.IsSelected).ToList();
                    int number = data.Min(t => t.Number);
                    //删除
                    data.ForEach(t => Infos.Remove(t));
                    context.Tracks.RemoveRange(data);
                    //更新排序
                    var orderList = Infos.Where(t => t.Number >= number).OrderBy(t => t.Number).ToList();
                    int num = 0;
                    orderList.ForEach(t =>
                    {
                        t.Number = number + num;
                        num++;
                    });
                    context.UpdateRange(Infos);
                    context.SaveChanges();

                }
              

              

            }
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
          
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
           
        }
    }
}
